package service

import (
	"fmt"
	"os"
	"oss-uploader/app/service/ali"
	"oss-uploader/app/service/qiniu"
	"path/filepath"
	"strings"
	"sync"
)

type uploadFileMap struct {
	key       string
	localFile string
}

var (
	OssType        string // oss类型：七牛云、阿里云
	UploadRootPath string // 本地上传根路径
	DestPathPrefix string // oss路径前缀
	WorkNum        int
	taskChan       chan uploadFileMap
	taskQueue      []uploadFileMap
	wg             sync.WaitGroup
)

func Work() {
	fileInfo, err := os.Stat(UploadRootPath)
	if err != nil {
		panic(err)
	}

	if !fileInfo.IsDir() {
		destPath := strings.Replace(filepath.Join(DestPathPrefix, fileInfo.Name()), "\\", "/", -1) // oss的文件路径
		uploadFile(destPath, UploadRootPath)
		return
	}

	taskChan = make(chan uploadFileMap)
	taskQueue = make([]uploadFileMap, 0)

	uploadDir(UploadRootPath)

	wg.Add(len(taskQueue))

	go func() {
		for _, v := range taskQueue {
			taskChan <- v
		}
	}()

	for i := 0; i < WorkNum; i++ {
		go task()
	}

	wg.Wait()
}

func uploadDir(sourcePath string) {
	dirList, err := os.ReadDir(sourcePath)
	if err != nil {
		fmt.Println(err)
		return
	}

	for _, dir := range dirList {
		localFile := filepath.Join(sourcePath, dir.Name()) // 本地上传的文件路径
		if dir.IsDir() {
			uploadDir(localFile)
			continue
		}

		destPath, _ := filepath.Rel(UploadRootPath, localFile)
		key := strings.Replace(filepath.Join(DestPathPrefix, destPath), "\\", "/", -1) // oss的文件路径
		taskQueue = append(taskQueue, uploadFileMap{
			key:       key,
			localFile: localFile,
		})
	}
}

func task() {
	for {
		select {
		case msg := <-taskChan:
			uploadFile(msg.key, msg.localFile)
			//fmt.Println(msg.key, msg.localFile)
			wg.Done()
		}
	}
}

func uploadFile(key, localFile string) {
	//fmt.Println(key, localFile)
	if OssType == "qiniu" {
		qiniu.UploadFile(key, localFile)
	} else if OssType == "ali" {
		ali.UploadFile(key, localFile)
	} else {
		fmt.Println("not support")
	}
}
